from flask import  Flask
from flask_cors import  CORS
from flask import request,jsonify
import json

from werkzeug.wrappers import response
from db import db


app = Flask(__name__)
CORS(app)

app.config['JSON_AS_ASCII'] = False

#测试
@app.route('/text/')
def text():
    return jsonify({'code':200,'mas':'asd你好45646'})


#展示商品列表
@app.route("/showgoods/")
def showgoods():
    id = request.args.get('id')
    if id:
        sql = "select * from goods where id=%d"%(int(id))
        res = db.find_all(sql)
    else:
        sql = "select * from goods"
        res = db.find_all(sql)
    return jsonify({"code":200,'list':res})

def get_data():
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    return data

#登录
@app.route("/klogin/",methods=["POST"])
def klogin():
    data = get_data()
    sql = "select * from users where name='%s' and password='%s'"%(data['name'],data['password'])
    res = db.find_one(sql)
    if res:
        if data['password'] == res['password']:
            return jsonify({"code":200,'mas':'登录成功','userid':res['id']})
        else:
            return jsonify({"code":20030,'mas':'用户名或密码错误'})
    else:
        return jsonify({"code":20020,'mas':'没有该用户请注册'})

#收藏
@app.route("/shoucang/")
def shoucang():
    id = int(request.args.get('id'))
    userid = int(request.args.get('userid'))
    type = int(request.args.get('type'))
    sql = "select * from shoucang where userid=%d and goodsid=%d"%(userid,id)
    res = db.find_one(sql)


    if type == 1:
        if res:
            return jsonify({'code':20020,'mas':'已收藏过该商品'})
        sql1 = "insert into shoucang values(%d,%d)"%(userid,id)
        db.insert(sql1)
        #加数量
        sql2= 'select * from goods where id=%d'%(id)
        res2 = db.find_one(sql2)
        count = int(res2['tcount'])+1
        sql3 = "update goods set tcount=%d where id=%d"%(count,id)
        db.insert(sql3)
        return jsonify({'code':200,'mas':'收藏成功','type':2})
    elif type == 2:
        #取消收藏
        sql6 = "delete from shoucang where userid=%d and goodsid=%d"%(userid,id)
        db.insert(sql6)
        sql4 = 'select * from goods where id=%d'%(id)
        res4 = db.find_one(sql4)
        count = int(res4['tcount'])-1
        sql5 = "update goods set tcount=%d where id=%d"%(count,id)
        db.insert(sql5)
        return jsonify({'code':2000,'mas':'取消收藏成功','type':1})

#我的收藏列表
@app.route('/myshoucang/')
def myshoucang():
    userid = int(request.args.get('userid'))
    print(userid)
    sql = "select * from (select * from users as u left join shoucang as s on u.id=s.userid where u.id=%d) as al left join goods as g on al.goodsid=g.id"%userid
    res = db.find_all(sql)

    return jsonify({"code":200,'list':res})





if __name__ == '__main__':
    app.run(debug=True,port=5000,host='127.0.0.1')







